package com.wimi.sf;

import com.google.gson.Gson;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * Hello world!
 *
 */
public class App 
{
	public static void main(String[] args) {
	    String host = "https://picread.market.alicloudapi.com";
	    String path = "/facecg";
	    String method = "POST";
	    String appcode = "916f1a22a26240dfa8957682f6416df6";
	    Map<String, String> headers = new HashMap<String, String>();
	    //最后在header中的格式(中间是英文空格)为uthorization:APPCODE 83359fd73fe94948385f570e3c139105
	    headers.put("Authorization", "APPCODE " + appcode);
	    //根据API的要求，定义相对应的Content-Type
	    headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	    Map<String, String> querys = new HashMap<String, String>();
	    Map<String, String> bodys = new HashMap<String, String>();
	    bodys.put("effect", "primary");
	    bodys.put("purl", "http://i.caigoubao.cc/627372/3.jpg");
	    bodys.put("srca", "图片base64编码");
	    bodys.put("srcb", "图片base64编码");
	    bodys.put("surl", "");
	    bodys.put("type", "video");
	    bodys.put("vurl", "http://i.caigoubao.cc/627372/data_A.mp4");


	    try {
	    	/**
	    	* 重要提示如下:
	    	* HttpUtils请从
	    	* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
	    	* 下载
	    	*
	    	* 相应的依赖请参照
	    	* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
	    	*/
	    	HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
	    	System.out.println(response.toString());
	    	
			/*
			 * Gson gson = new Gson(); JsonRootBean jrb =
			 * gson.fromJson(EntityUtils.toString(response.getEntity()),JsonRootBean.class);
			 * 
			 * if( 200 == jrb.getStatus() ) {
			 * downloadUsingStream(jrb.getMsg(),"output.mp4"); }
			 */
	    	
	    	//获取response的body
	    	System.out.println(EntityUtils.toString(response.getEntity()));
	    } catch (Exception e) {
	    	e.printStackTrace();
	    }
	}
	
	private static void downloadUsingStream(String urlStr, String file) throws IOException{
        URL url = new URL(urlStr);
        BufferedInputStream bis = new BufferedInputStream(url.openStream());
        FileOutputStream fis = new FileOutputStream(file);
        byte[] buffer = new byte[102400];
        int count=0;
        while((count = bis.read(buffer,0,1024)) != -1)
        {
            fis.write(buffer, 0, count);
        }
        fis.close();
        bis.close();
    }
}
